<template>
  <div>
    <!-- 这个是用来设置单个文件上传的插件 -->
      <el-upload class="upload-demo" 
          :data="dataObj"
          :action="action" 
          list-type="picture"
          :show-file-list="true"
          :limit="1"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
      </el-upload>
  </div>
</template>

<script>
import axios from 'axios';
import {v4 as getUUID} from 'uuid';
export default {
  props:["imgurl"],
  data() {
    return {
      url:"",
      action:"",
      dataObj:{
        key:"",
        OSSAccessKeyId:"",
        policy:"",
        signature:"",
      },
      fileList: [
        {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'} 
      ]
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'||file.type==="image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      return new Promise((resolve,rejects)=>{
        axios.get("http://localhost:88/api/thirdparty/oss/policy").then(({data})=>{
          let uuidStr=getUUID();
          this.dataObj.OSSAccessKeyId=data.data.accessId;
          this.dataObj.policy=data.data.policy;
          this.dataObj.signature=data.data.signature;
          this.dataObj.key=data.data.dir+uuidStr+"_${filename}";
          this.url=data.data.host+"/"+data.data.dir+uuidStr+"_"+file.name;
          console.log(file);
          this.action=data.data.host;
          resolve(true);
        }).catch((err)=>{
          this.$message.error('无法获取签名，具体信息：'+err.message);
          rejects(false);
        })
      })
      
    },
    handleAvatarSuccess(res, file) {
      console.log(res,file)
      this.$emit("input",this.url)
      this.imageUrl = URL.createObjectURL(file.raw);
    }
  }
}
</script>

<style></style>